package hn.cch.caffeine.service.impl;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.stats.CacheStats;
import hn.cch.cache.constant.CacheConstant;
import hn.cch.caffeine.service.CaffeineService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
public class CaffeineServiceImpl implements CaffeineService {

    private static final Logger logger = LoggerFactory.getLogger(CaffeineServiceImpl.class);


    @Autowired
    public Cache<Object, Object> cache;


    @Cacheable(value = {CacheConstant.CACHE_NAME}, key = "#key")
    public String getCache(String key) {


        logger.info("getCache key:{}", key);
        return String.format("getCache:%s", key);
    }

    @CachePut(value = {CacheConstant.CACHE_NAME}, key = "#key")
    public String setCache(String key) {
        logger.info("setCache key:{}", key);
        return String.format("setCache:%s", key);
    }


    @CacheEvict(value = {CacheConstant.CACHE_NAME}, key = "#key")
    public String delCache(String key) {
        logger.info("delCache key:{}", key);
        return String.format("delCache:%s", key);
    }

    public String putCache(String key, String value) {
        cache.put(key, value);
        return String.format("key:value=%s:%s", key, value);
    }

    public String getCacheStats() {
        logger.info("cache map size:{}", cache.asMap().size());
        CacheStats cacheStats = cache.stats();
        return cacheStats.toString();
    }

}
